package com.blog.zip.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.blog.zip.bean.Product;
import com.blog.zip.bean.RespBean;
import com.blog.zip.bean.User;
import com.blog.zip.mapper.ProductMapper;
import com.blog.zip.mapper.UserMapper;
import com.blog.zip.service.TokenService;
import com.blog.zip.util.TokenUtil;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
public class UserController {

    @Autowired
    private
    UserMapper userMapper;

    @Autowired
    private
    ProductMapper productMapper;

    @Autowired
    TokenService tokenService;


    //用户登录
    @PostMapping("/user/login")
    public Object userLogin(@RequestBody User user, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        User u;
        if (Objects.equals(user.getUserName(), "")) {
            jsonObject.put("msg", "login failed,userName is empty");
            jsonObject.put("code", 300);
            return jsonObject;
        }
        if (Objects.equals(user.getUserPassword(), "")) {
            jsonObject.put("msg", "login failed,password is empty");
            jsonObject.put("code", 301);
            return jsonObject;
        }
        u = userMapper.getUserByPassword(user.getUserName(), user.getUserPassword());
        if (u == null || !u.getUserPassword().equals(user.getUserPassword())) {
            jsonObject.put("msg", "login failed,name or password dot not match");
            jsonObject.put("code", 302);
        } else {
//            System.out.println(u);
            Map<String, Object> map = new HashMap<>();
//            map.put("id",u.getOid());
            map.put("id", u.getOid());
            map.put("username", u.getUserName());
            map.put("password", u.getUserPassword());
            String token = TokenUtil.getToken(map);
            jsonObject.put("token", token);
            jsonObject.put("msg", "success");
            jsonObject.put("code", 200);
//            session.setAttribute("loginUser", u);

            request.getSession().setAttribute("loginUser", u);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);

//            User loginUser = (User) request.getSession().getAttribute("loginUser");
//            System.out.println(loginUser);

        }
        return jsonObject;
    }

    //测试需要使用token请求的接口

    @PostMapping("/user/message")
    public Object getUserMessageByToken(HttpServletRequest request) {
        //System.out.println(TokenUtil.getTokenUserId());
        // 从token中获取用户id
        String token = request.getHeader("B-Token");
        DecodedJWT verify = TokenUtil.verify(token);
        String id = verify.getClaim("id").asString();
        // 结束
        Object userInfo = userMapper.getUserByIdV2(id);
        //1	ziptest	http://120.78.171.106:8080	testRole	https://b3logfile.com/avatar/1631789492977_1631861768507.jpeg?imageView2/1/w/128/h/128/interlace/0/q/100	ziptest	2	919496
        //1631789583088	zipfang	http://120.78.171.206:8080	adminRole	https://b3logfile.com/avatar/1631789492977_1631861768507.jpeg?imageView2/1/w/128/h/128/interlace/0/q/100	zipfang	1631789492977	919496
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "用户信息获取成功");
        jsonObject.put("data", userInfo);

        return jsonObject;
    }

    @GetMapping("/admin/user/get")
    public RespBean getRoleList() {
        List<Map<String, Object>> list = userMapper.getUserList();
        return new RespBean(200, "success", list);
    }

    @PostMapping("/admin/user/update")
    public RespBean updateRoleList(@RequestBody Map m) {
        userMapper.updateUserList(m);
        return new RespBean(200, "update success");
    }

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id) {
        return userMapper.getUserById(id);
    }

    @GetMapping("/user")
    public User insertUser(User user) {
        userMapper.insertUser(user);
        return user;
    }

    @GetMapping("/pro/{id}")
    public Product getProduct(@PathVariable("id") Integer id) {
        return productMapper.getProductById(id);
    }

    @GetMapping("/pro")
    public Product insertProduct(Product pro) {
        productMapper.insertProduct(pro);
        return pro;
    }
}
